<?php

namespace App\Models\Train\TrainIssues;

use App\Trip\Traits\ModelDateTrait;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

//use Jenssegers\Mongodb\Eloquent\Model;

/**
 * App\Models\Train\TrainIssues\TrainIssueRelation
 *
 * @property int         $id
 * @property int         $issue_id    问题id
 * @property int         $order_state 订单状态
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @method static Builder|TrainIssueRelation newModelQuery()
 * @method static Builder|TrainIssueRelation newQuery()
 * @method static Builder|TrainIssueRelation query()
 * @method static Builder|TrainIssueRelation whereCreatedAt($value)
 * @method static Builder|TrainIssueRelation whereId($value)
 * @method static Builder|TrainIssueRelation whereIssueId($value)
 * @method static Builder|TrainIssueRelation whereOrderState($value)
 * @method static Builder|TrainIssueRelation whereUpdatedAt($value)
 * @mixin Eloquent
 */
class TrainIssueRelation extends Model
{
    use ModelDateTrait;

//	protected $connection = 'mongodb';
//	protected $collection = 'train_issue_relation';
    protected $table = 'train_issue_relation';
    protected $fillable
                     = [
            "issue_id",
            "order_state",
        ];

    public function addRelation(TrainIssue $issue, int $order_state)
    {
        if ($r = $this->findByIssueIdAndOrderState($issue->getIssueId(), $order_state)) {
            return $r;
        } else {
            return $this->create([
                "issue_id"    => $issue->getIssueId(),
                "order_state" => $order_state,
            ]);
        }
    }

    public function findByIssueIdAndOrderState($issue_id, $order_state)
    {
        $cache_key = "TrainIssueRelation:{$issue_id}:{$order_state}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $res = $this->where('issue_id', $issue_id)->where('order_state', $order_state)->first();
        if ($res) {
            Cache::put($cache_key, $res, config('trip.ttl.day') * 10);
        }
        return $res;
    }

    public function getIssueIdsByOrderState(int $order_state)
    {
        return $this->where('order_state', $order_state)->pluck('issue_id')->toArray();
    }

}
